import { UploadService } from 'src/app/services/upload.service';
import { Component, Input, OnInit } from '@angular/core';
import { NzMessageService, NzModalRef, NzUploadFile } from 'ng-zorro-antd';
import { Observable, Observer } from 'rxjs';

@Component({
  selector: 'zepride-img-modal',
  templateUrl: './img-modal.component.html',
  styleUrls: ['./img-modal.component.less']
})
export class ImgModalComponent implements OnInit {
  @Input() dm: any;
  @Input() curImage: any = {};
  imageStores = [];
  constructor(
    private modal: NzModalRef,
    public uploadSvr: UploadService,
    protected msg: NzMessageService
  ) { }

  async ngOnInit() {
    await this.getBackgrounds();
  }

  async getBackgrounds() {
    let result = await this.uploadSvr.getFiles('bidBackground');
    this.imageStores = result.objects;
    if (this.curImage) {
      this.curImage = this.imageStores.find(x => x.etag == this.curImage.etag);
    }
    else {
      this.curImage = this.imageStores[0];
    }

    this.curImage.selected = true;
  }

  selectImg(item) {
    this.imageStores.map(x => x.selected = false);
    item.selected = true;
    this.curImage = item;
  }

  previewImage: string | undefined = '';
  previewVisible = false;
  handlePreview = async (item) => {
    this.previewImage = item.url;
    this.previewVisible = true;
  };

  ok() {
    this.modal.close({
      backgroundImage: this.curImage
    });
  }

  cancel() {
    this.modal.close();
  }

  async delImage() {
    await this.uploadSvr.delFileByName(this.curImage.name);
    this.curImage = null;
    await this.getBackgrounds();
  }

  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/bmp';
      if (!isJpgOrPng) {
        this.msg.error('只能上传图片文件！');
        observer.complete();
        return;
      }
      const isLt2M = file.size! / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.msg.error('图片文件不能超过2MB!');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  }

  private loading = false;
  uploadFileName = '';
  handleChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        this.loading = true;
        break;
      case 'done':
        this.getBase64(info.file!.originFileObj!, (img: string) => {
          this.loading = false;
          this.getBackgrounds();
        });
        break;
      case 'error':
        this.msg.error('Network error');
        this.loading = false;
        break;
    }
  }

  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }

}
